package com.common.loadbalance.impl;

import com.common.loadbalance.CommonLoadBalance;
import com.common.tools.CommonTool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author Zixiang Hu
 * @description 源地址哈希，负载均衡
 * @create 2021-04-16-11:15
 */
public class IpHashLoadBalance implements CommonLoadBalance {
    @Override
    public String getServerAddr(List<String> servers) {
        String localIPList = CommonTool.getLocalIPList();
        int idx = hash(localIPList) % servers.size();
        return servers.get(idx);
    }

    /**
     * 借用HashMap的哈希扰动函数
     * @param key
     * @return
     */
    public int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

}
